"""
社交互动视图
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from .models import Post, Comment, Like, PostImage
from .serializers import PostSerializer, CommentSerializer, LikeSerializer
from utils.image_utils import validate_image, compress_image


class PostViewSet(viewsets.ModelViewSet):
    """动态视图集"""
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    throttle_classes = []

    def get_throttles(self):
        """根据动作设置节流策略"""
        from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
        action = getattr(self, 'action', None)
        if action in ['like', 'comment', 'upload_images']:
            return [UserRateThrottle()]
        return super().get_throttles()
    
    def get_queryset(self):
        """优化查询，使用select_related和prefetch_related减少数据库查询"""
        from django.db.models import Q
        
        queryset = super().get_queryset()
        # 使用select_related优化外键查询（user, route_plan）
        # 使用prefetch_related优化多对多和反向关联查询（post_images, comments, likes）
        queryset = queryset.select_related('user', 'route_plan').prefetch_related(
            'post_images', 'comments', 'likes'
        )
        
        # 支持按用户ID筛选
        user_id = self.request.query_params.get('user_id', None)
        if user_id:
            queryset = queryset.filter(user_id=user_id)
        
        # 支持搜索（按内容搜索）
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(Q(content__icontains=search))
        
        # 支持按时间筛选
        date_from = self.request.query_params.get('date_from', None)
        date_to = self.request.query_params.get('date_to', None)
        if date_from:
            queryset = queryset.filter(created_at__gte=date_from)
        if date_to:
            queryset = queryset.filter(created_at__lte=date_to)
        
        # 支持排序
        ordering = self.request.query_params.get('ordering', '-created_at')
        if ordering:
            queryset = queryset.order_by(ordering)
        else:
            queryset = queryset.order_by('-created_at')
        
        return queryset
    
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
    
    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['request'] = self.request
        return context
    
    def list(self, request, *args, **kwargs):
        """分页返回动态列表"""
        from rest_framework.pagination import PageNumberPagination
        from django.db.models import Q
        queryset = self.get_queryset()
        # 简单过滤：关键词、时间范围、按用户
        keyword = request.query_params.get('search')
        if keyword:
            queryset = queryset.filter(Q(content__icontains=keyword) | Q(user__username__icontains=keyword))
        date_from = request.query_params.get('date_from')
        date_to = request.query_params.get('date_to')
        if date_from:
            queryset = queryset.filter(created_at__date__gte=date_from)
        if date_to:
            queryset = queryset.filter(created_at__date__lte=date_to)
        user_id = request.query_params.get('user_id')
        if user_id:
            queryset = queryset.filter(user_id=user_id)
        ordering = request.query_params.get('ordering')
        if ordering:
            # 安全控制：仅允许部分字段排序
            allowed = {'created_at', '-created_at', 'likes_count', '-likes_count'}
            if ordering in allowed:
                queryset = queryset.order_by(ordering)
        paginator = PageNumberPagination()
        try:
            page_size = int(request.query_params.get('page_size', 20))
        except Exception:
            page_size = 20
        paginator.page_size = page_size
        page = paginator.paginate_queryset(queryset, request, view=self)
        serializer = self.get_serializer(page, many=True)
        return paginator.get_paginated_response(serializer.data)
    
    def update(self, request, *args, **kwargs):
        """更新动态 - 只能更新自己的动态"""
        instance = self.get_object()
        if instance.user != request.user:
            return Response(
                {'error': '无权编辑此动态'},
                status=status.HTTP_403_FORBIDDEN
            )
        return super().update(request, *args, **kwargs)
    
    def destroy(self, request, *args, **kwargs):
        """删除动态 - 只能删除自己的动态"""
        instance = self.get_object()
        if instance.user != request.user:
            return Response(
                {'error': '无权删除此动态'},
                status=status.HTTP_403_FORBIDDEN
            )
        return super().destroy(request, *args, **kwargs)
    
    @action(detail=True, methods=['post', 'delete'])
    def like(self, request, pk=None):
        """点赞/取消点赞"""
        post = self.get_object()
        
        if request.method == 'POST':
            like, created = Like.objects.get_or_create(
                user=request.user,
                post=post
            )
            if created:
                return Response({'message': '点赞成功'}, status=status.HTTP_201_CREATED)
            return Response({'message': '已点赞'}, status=status.HTTP_200_OK)
        elif request.method == 'DELETE':
            Like.objects.filter(user=request.user, post=post).delete()
            return Response({'message': '取消点赞成功'}, status=status.HTTP_200_OK)
    
    @action(detail=True, methods=['post'])
    def comment(self, request, pk=None):
        """添加评论"""
        post = self.get_object()
        serializer = CommentSerializer(data=request.data)
        
        if serializer.is_valid():
            serializer.save(user=request.user, post=post)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['get'])
    def comments(self, request, pk=None):
        """获取评论列表（分页）"""
        post = self.get_object()
        from rest_framework.pagination import PageNumberPagination
        comments_qs = Comment.objects.filter(post=post).select_related('user').order_by('-created_at')
        paginator = PageNumberPagination()
        try:
            page_size = int(request.query_params.get('page_size', 20))
        except Exception:
            page_size = 20
        paginator.page_size = page_size
        page = paginator.paginate_queryset(comments_qs, request, view=self)
        serializer = CommentSerializer(page, many=True)
        return paginator.get_paginated_response(serializer.data)
    
    @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated])
    def upload_images(self, request, pk=None):
        """上传动态图片（支持多图）"""
        post = self.get_object()
        
        # 检查权限：只能为自己的动态上传图片
        if post.user != request.user:
            return Response(
                {'error': '无权操作'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        if 'images' not in request.FILES:
            return Response(
                {'error': '请选择要上传的图片'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        uploaded_images = []
        errors = []
        
        # 处理多个图片文件
        images = request.FILES.getlist('images')
        for image_file in images:
            # 验证图片
            is_valid, error_message = validate_image(image_file)
            if not is_valid:
                errors.append(f'{image_file.name}: {error_message}')
                continue
            
            try:
                # 压缩图片
                compressed_image = compress_image(image_file, max_size=(1200, 1200), quality=85)
                
                # 创建图片记录
                image_obj = PostImage.objects.create(
                    post=post,
                    image=compressed_image
                )
                # 构建完整的图片URL
                image_url = image_obj.image.url
                if request:
                    image_url = request.build_absolute_uri(image_obj.image.url)
                
                uploaded_images.append({
                    'id': image_obj.id,
                    'image': image_url
                })
            except Exception as e:
                errors.append(f'{image_file.name}: {str(e)}')
        
        if uploaded_images:
            return Response({
                'message': f'成功上传{len(uploaded_images)}张图片',
                'images': uploaded_images,
                'errors': errors if errors else None
            }, status=status.HTTP_201_CREATED)
        else:
            return Response({
                'error': '所有图片上传失败',
                'errors': errors
            }, status=status.HTTP_400_BAD_REQUEST)


class CommentViewSet(viewsets.ModelViewSet):
    """评论视图集"""
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    
    def get_queryset(self):
        """优化查询，使用select_related优化外键查询"""
        queryset = super().get_queryset()
        queryset = queryset.select_related('user', 'post')
        return queryset.order_by('-created_at')
    
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

